package com.bms.admin.config;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.afterturn.easypoi.cache.manager.FileLoaderImpl;
import cn.afterturn.easypoi.cache.manager.IFileLoader;

public class EasypoiFileLoader implements IFileLoader {

	private static final Logger LOGGER = LoggerFactory.getLogger(FileLoaderImpl.class);

	@Override
	public byte[] getFile(String url) {
		InputStream fileis = null;
		ByteArrayOutputStream baos = null;
		try {

			// 判断是否是网络地址
			if (url.startsWith("http")) {
				HttpClient httpClient = new DefaultHttpClient();
				HttpGet httpGet = new HttpGet();
				httpGet.setURI(new URI(url));
				HttpResponse response = httpClient.execute(httpGet);
				fileis = response.getEntity().getContent();
			} else {
				// 先用绝对路径查询,再查询相对路径
				try {
					fileis = new FileInputStream(url);
				} catch (FileNotFoundException e) {
					// 获取项目文件
					fileis = FileLoaderImpl.class.getClassLoader().getResourceAsStream(url);
				}
			}

			baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len;
			while ((len = fileis.read(buffer)) > -1) {
				baos.write(buffer, 0, len);
			}
			baos.flush();
			return baos.toByteArray();
		} catch (IOException e) {
			LOGGER.error(e.getMessage(), e);
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(fileis);
			IOUtils.closeQuietly(baos);
		}
		LOGGER.error(fileis + "这个路径文件没有找到,请查询");
		return null;
	}

}
